package com.xkdx.guangguang.application;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.xkdx.caipiao.MainTabActivity;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.module.cache.XkCache;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class MyApplication extends Application {
	public static ImageLoader imageLoader = ImageLoader.getInstance();
	private static MyApplication mInstance = null;
	public static boolean m_bKeyRight = true;
	public BMapManager mBMapManager = null;
//	public static final String strKey = "vSwmt16FVw5usIfNud8aYGNG";
    public static final String strKey = "obTj5AnMqMzH8KdxfBoxwyza";
	public static LocationClient mLocClient;
	public static MyLocationListenner myLocationListenner;
	private static Application mApp = null;
	private SharePrefenceUtil sp;
	private int count = 0;
	public static int redpackageNum;

	// 充值和购买红包的返回问题，第二个参数是用于处理
	public static boolean isClosePayDetail = false;
	public static boolean isClosePacketList = false;
	public static boolean isOrderPay = false;
	public static boolean isDetails = false;
	public static boolean isRedpakeDetail = false;
    public static boolean isLocating = false;
	// 当前是否正在付款
	public static boolean isPaying = false;

	// 推送定时器
	Timer timer;
	// yes:已加载notice，从而可以直接返回
	public boolean isLaunchedNotification;
	// 是否显示了notice ，true：显示了notice
	public boolean isPushLunch;
	// 推送变量
	public boolean isPushSevenColor;
	public boolean isPushLottery;
	public boolean isPushThree;
	public boolean isPushFive;

	/*
	 * 注意：为了给用户提供更安全的服务，Android SDK自v2.1.3版本开始采用了全新的Key验证体系。
	 * 因此，当您选择使用v2.1.3及之后版本的SDK时，需要到新的Key申请页面进行全新Key的申请， 申请及配置流程请参考开发指南的对应章节
	 */

	@Override
	public void onCreate() {
		super.onCreate();

		mLocClient = new LocationClient(this);
		setLocationOption();
		mApp = this;
		myLocationListenner = new MyLocationListenner();
		mLocClient.registerLocationListener(myLocationListenner);
        isLocating =  true;
		mLocClient.start();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		mInstance = this;
		XkCache.initCacheManager(this);
		com.xkdx.caipiao.module.cache.XkCache.initCacheManager(this);
		isPushSevenColor = true;
		isPushLottery = true;
		isPushThree = true;
		isPushFive = true;
		initEngineManager(this);
		startPushService();
		startPushServiceForSelf();

	}

	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(false); // 打开gps
		option.setCoorType("bd0911"); // 设置坐标类型
		option.setAddrType("all"); // 设置地址信息，仅设置为“all”时有地址信息，默认无地址信息
		option.setScanSpan(10000); // 设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
		mLocClient.setLocOption(option);
	}

	public void initEngineManager(Context context) {
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(strKey, new MyGeneralListener())) {
			Toast.makeText(MyApplication.getInstance().getApplicationContext(),
					"BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
		}
	}

	public static MyApplication getInstance() {
		if (null == mInstance) {
			mInstance = new MyApplication();
		}
		return mInstance;
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	public static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
            isLocating = false;
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(
						MyApplication.getInstance().getApplicationContext(),
						"您的网络出错啦！", Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(
						MyApplication.getInstance().getApplicationContext(),
						"输入正确的检索条件！", Toast.LENGTH_LONG).show();
			}
		}

		@Override
		public void onGetPermissionState(int iError) {
            isLocating = false;
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误：
				// Toast.makeText(MyApplication.getInstance().getApplicationContext(),
				// "请在 DemoApplication.java文件输入正确的授权Key！",
				// Toast.LENGTH_LONG).show();
				// m_bKeyRight = false;
			}
		}
	}

	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// Log.i("ShopFragment", location.getAddrStr());
            isLocating = false;
			if (location == null || location.getAddrStr() == null
					|| location.getAddrStr().equals("")) {
				IConstants.currentPosition = getResources().getString(
						R.string.not_location_current_position);
				com.xkdx.caipiao.statics.IConstants.currentPosition = getResources().getString(
						R.string.not_location_current_position);
				return;
			}

			// //鉴于百度地图误差500米左右，进行定位
			IConstants.lat = location.getLatitude() > 0.0 ? location
					.getLatitude() + IConstants.latCheck : location
					.getLatitude();
			com.xkdx.caipiao.statics.IConstants.lat = location.getLatitude() > 0.0 ? location
					.getLatitude() + IConstants.latCheck : location
					.getLatitude();
			IConstants.lon = location.getLongitude() > 0.0 ? location
					.getLongitude() + IConstants.lonCheck : location
					.getLongitude();
			com.xkdx.caipiao.statics.IConstants.lon = location.getLongitude() > 0.0 ? location
					.getLongitude() + IConstants.lonCheck : location
					.getLongitude();

			// IConstants.lat = location.getLatitude();
			// IConstants.lon = location.getLongitude();

			IConstants.currentPosition = "你的当前位置：" + location.getAddrStr();
			com.xkdx.caipiao.statics.IConstants.currentPosition = "你的当前位置：" + location.getAddrStr();

			if (location.getCity() == null) {
				return;
			} else {
				SharePrefenceUtil su_city = new SharePrefenceUtil(
						getApplicationContext(), IConstants.SP_CITY);
                IConstants.isLocationSuccess = true;
//				su_city.setLocationCityName(location.getCity().substring(0, 2));
				su_city.setLocationCityName(location.getCity());
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}

		}
	}

	public static Application getApplication() {
		return mApp;
	}

	private void startPushService() {
		Intent pushservice = new Intent("com.xkdx.guangguang.service.push");
		startService(pushservice);
	}

	private void startPushServiceForSelf() {
		Intent pushservice = new Intent(
				"com.xkdx.guangguang.service.pushforself");

		startService(pushservice);
	}
	
	public void startMyNotice() {
		if (isLaunchedNotification) {
			return;
		} else {
			isLaunchedNotification = true;
		}
		if (isPushSevenColor || isPushLottery || isPushThree || isPushFive) {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			int day = getWeekAndDay();
			int timeWhen = 0;// 多长时间后提示用户
			int timeWhenShadow = 0;// 用于备份timeWhen
			int KNINE = 21 * 60 * 60;
			int KDAY = 24 * 60 * 60;
			int curSec = curDate.getHours() * 60 * 60 + (curDate.getMinutes())
					* 60 + curDate.getSeconds();
			if (isPushSevenColor) {
				if (2 == day || 5 == day || 7 == day) {
					if (curDate.getHours() < 21) {
						timeWhen = KNINE - curSec;
					} else {
						timeWhen = KNINE + KDAY * 2 - curSec;
						if (2 == day) {
							// 周2到周5要多一天，就加一天
							timeWhen = KNINE + KDAY * 3 - curSec;
						}
					}
				} else if (1 == day || 4 == day || 6 == day) {
					timeWhen = KNINE + KDAY - curDate.getHours() * 60 * 60
							- (curDate.getMinutes()) * 60
							- curDate.getSeconds();
				} else if (3 == day) {
					timeWhen = KNINE + KDAY * 2 - curSec;
				}
				timeWhenShadow = timeWhen;
			}
			if (isPushLottery) {
				if (1 == day || 3 == day || 6 == day) {
					if (curDate.getHours() < 21) {
						timeWhen = 21 * 60 * 60 - curSec;
					} else {
						timeWhen = KNINE + KDAY * 2 - curSec;
						if (3 == day) {
							timeWhen = KNINE + KDAY * 3 - curSec;
						}
					}
				} else if (7 == day || 2 == day || 5 == day) {
					timeWhen = KNINE + KDAY - curSec;
				} else if (4 == day) {
					timeWhen = KNINE + KDAY * 2 - curSec;
				}
				timeWhenShadow = timeWhen < timeWhenShadow ? timeWhen
						: timeWhenShadow;
			} else if (isPushThree) {
				if (curDate.getHours() < 21) {
					timeWhen = KNINE - curSec;
				} else {
					timeWhen = KNINE + KDAY - curSec;
				}
				timeWhenShadow = timeWhen < timeWhenShadow ? timeWhen
						: timeWhenShadow;
			} else if (isPushFive) {
				if (curDate.getHours() < 21) {
					timeWhen = KNINE - curSec;
				} else {
					timeWhen = KNINE + KDAY - curSec;
				}
				timeWhenShadow = timeWhen < timeWhenShadow ? timeWhen
						: timeWhenShadow;
			}
			timer = new Timer(true);
			timer.schedule(new RemindTask(), timeWhenShadow * 1000);// 10000);
		}
	}

	private int getWeekAndDay() {
		Calendar calendar = Calendar.getInstance();
		// 获取当前时间为本月的第几周
		int week = calendar.get(Calendar.WEEK_OF_MONTH);
		// 获取当前时间为本周的第几天
		int day = calendar.get(Calendar.DAY_OF_WEEK);
		if (day == 1) {
			day = 7;
			week = week - 1;
		} else {
			day = day - 1;
		}
		System.out.println("今天是本月的第" + week + "周" + ",星期" + (day));
		return day;
	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(Integer.MAX_VALUE);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			Toast.makeText(mContext, serviceList.get(i).service.getClassName(),
					Toast.LENGTH_SHORT).show();

			if (serviceList.get(i).service.getClassName().equals(className)) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}
	
	class RemindTask extends TimerTask {
		public void run() {
			notice();
		}
	};

	void notice() {
		isPushLunch = true;
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		String title = "彩票开奖啦";
		String content = "您定制的彩票信息已开奖，快去查看哦";

		Notification notification = new Notification(R.drawable.xk_lg_caipiao,
				"通知领取彩票", System.currentTimeMillis());
		Intent intent = new Intent(this, MainTabActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("notification", "yes");

		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

		notification.setLatestEventInfo(this, title, content, pi);
		nm.notify(1111, notification);
	}

}